
const form = document.querySelector('form')
console.log(form);
const nameInp = document.querySelector('.username')
const pwdInp = document.querySelector('.password')
console.log(nameInp);
console.log(pwdInp);
const errBox = document.querySelector('.error')
console.log(errBox);
// const id = window.localStorage.getItem('id')
// console.log(id);
// const token = window.localStorage.getItem('token')
// console.log(token);

form.addEventListener('submit', e => {
    e.preventDefault()

    const name = nameInp.value 
    const pwd = pwdInp.value 

    if (!name || !pwd) return alert ('请求填写表格 (#^_^#) ')

    const xhr = new XMLHttpRequest()
    xhr.open('POST','http://localhost:8888/users/login')
    xhr.onload = function () {
        const res = JSON.parse(xhr.responseText)
console.log(res);
        if (res.code === 0) {
            errBox.style.display = 'block'
            return
        }

        window.localStorage.setItem('id', res.user.id)
        window.localStorage.setItem('token',res.token)
        window.location.href = 'http://www.baidu.com'
    }
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    xhr.send(`username=${ name }&password=${ pwd }`)
})